package email

import (
	"fmt"
	"gopkg.in/gomail.v2"
	"time"
)

type emailMessage struct {
	m *gomail.Message
	d *gomail.Dialer
}

var (
	emailDataChan = make(chan *emailMessage, 100000)
)

type Email struct {
	Dsn      string `json:"dsn"`
	Port     int    `json:"port"`
	Username string `json:"username"`
	Password string `json:"password"`
	Env      string `json:"env"`
	From     string `json:"from"`
	FromName string `json:"from_name"`
	To       string `json:"to"`
}

var e *Email

func Init(email *Email) {
	e = email
	go sendEmail()
}

func sendEmail() {
	for {
		select {
		case em := <-emailDataChan:
			err := em.d.DialAndSend(em.m)
			if err != nil {
				fmt.Println("邮件发送失败：", err)
			}
		default:
			time.Sleep(time.Second)
		}
	}
}

func SendToChan(subject, body string) {
	m := gomail.NewMessage()
	m.SetHeader("From", m.FormatAddress(e.From, e.FromName))      //这种方式可以添加别名，即“XX官方”
	m.SetHeader("To", e.To)                                       //发送给多个用户
	m.SetHeader("Subject", fmt.Sprintf("【%v】%v", e.Env, subject)) //设置邮件主题
	m.SetBody("text/html", body)                                  //设置邮件正文
	d := gomail.NewDialer(e.Dsn, e.Port, e.Username, e.Password)
	emailDataChan <- &emailMessage{d: d, m: m}
}
